<?php

// This script accesses http://rs.gbif.org/vocabulary/iso/3166-1_alpha2.xml
// and returns an array of country code with country name as index.

	$country = array();

function build2DigitCountryCode() {
	
	$name = strtoupper($name);
	
	$countries_voc = "http://rs.gbif.org/vocabulary/iso/3166-1_alpha2.xml";
	
	$countries_xml = new SimpleXMLElement($countries_voc, NULL, TRUE);
	$countries_xml->registerXPathNamespace('x', 'http://rs.gbif.org/thesaurus/');
	
	// Calculate the number of available concepts
	
	$country_number = count($countries_xml->xpath('//x:concept'));
	
	$country_name = $countries_xml->xpath('//x:preferred/x:term[1]/@dc:title');
	$country_identifier = $countries_xml->xpath('//x:concept/@dc:identifier'); 
	$country_fullname = array();
	$country_code = array();
	global $country;
	
	
	foreach ($country_name as $simObj) {
		array_push($country_fullname, get_object_vars($simObj));
	}
	
	foreach ($country_identifier as $simObj) {
		array_push($country_code, get_object_vars($simObj));
	}
	
	for ( $i = 0 ; $i < $country_number ; $i++ ) {
		$key = $country_fullname[$i]["@attributes"]['title'];
		$value = $country_code[$i]["@attributes"]['identifier'];
		$country[$key] = $value;
	}
		
}

function get2DigitCountryCode($name) {
	global $country;
	return $country[$name];
}

?>